(function(){
function Dashboard(){

var $colsAccepted = {
    title: '操作',
    field: 'operation',
    formatter: function(value, row, index){
        return '<span class="label label-danger arrowed-right key-delete">移除</span>'
    }
}
var $colsRejected = $colsDenied = $colsAccepted;
var $colsPre = {
    title: '操作',
    field: 'operation',
    formatter: function(value, row, index){
        return [
            '<span class="label label-success key-accept">接受</span>',
            '<span class="label label-warning key-reject">拒绝</span>',
            '<span class="label label-danger key-deny">禁止</span>',
        ].join('');
    }
}

$colsAccepted = $baseCols.concat($colsAccepted);
var $optsAccepted = {
    sidePagination: 'client',
    columns: $colsAccepted,
    toolbar: '#accepted .toolbar'
}
Object.assign($optsAccepted, $baseOpts);

$colsPre = $baseCols.concat($colsPre);
var $optsPre = {
    sidePagination: 'client',    
    columns: $colsPre,
    toolbar: '#pre .toolbar'
}
Object.assign($optsPre, $baseOpts);

$colsRejected = $baseCols.concat($colsRejected);
var $optsRejected = {
    sidePagination: 'client',    
    columns: $colsRejected,
    toolbar: '#rejected .toolbar'
}
Object.assign($optsRejected, $baseOpts);

$colsDenied = $baseCols.concat($colsDenied);
var $optsDenied = {
    sidePagination: 'client',    
    columns: $colsDenied,
    toolbar: '#denied .toolbar'
}
Object.assign($optsDenied, $baseOpts);

/*************************************************************************************/

var breadcrumb = new Breadcurmb({
    prefix: [],
    curr: ' 仪表盘'
});

var chartView = Backbone.View.extend({});
var chartModel = Backbone.Model.extend({});
var tableView = Backbone.View.extend({});

var MainView = Backbone.View.extend({
    // el与initialize一样是bk的关键字, 不能重命名为其它
    el: '#page-cnt',
    template:  _.template($("#tpl-dashboard").html()),
    events: {
        'click #minions-accepted .key-delete': 'keysOperation',
        'click #minions-pre .key-accept': 'keysOperation',
        'click #minions-pre .key-reject': 'keysOperation',
        'click #minions-pre .key-deny': 'keysOperation',
        'click #minions-rejected .key-delete': 'keysOperation',
        'click #minions-denied .key-delete': 'keysOperation',
    },
    initialize: function() {
        // 创建面包屑视图
        this.breadcrumbView = new BreadcrumbView({model: breadcrumb});
        this.render();
    },
    render: function(){
        this.$el.html(this.template());
        
        $('#minions-accepted').bootstrapTable($optsAccepted);
        $('#minions-pre').bootstrapTable($optsPre);
        $('#minions-rejected').bootstrapTable($optsRejected);
        $('#minions-denied').bootstrapTable($optsDenied);
        this.refreshKeys();
        this.refreshStatus();
    },
    refreshKeys: function(){
        var self = this;
        $.ajax({
            type: 'GET',
            url: apiList.key.query,
            success: function(result){
                result = result.return[0].data.return;
                self.renderKeyChart(result);
                self.renderKeyTable(result);
            }
        });
    },
    refreshStatus: function(){
        var self = this;
        $.ajax({
            type: 'GET',
            url: apiList.health,
            success: function(result){
                result = result.return[0];
                self.renderStatusChart(result);
            }
        });
    },
    renderKeyChart: function(data){
        var keyListWidget = echarts.init(document.getElementById('key-chart'));
        var option = {
            title: {
                text: '节点key列表'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b}: {c} ({d}%)"
            },
            legend: {                           // 图例
                orient: 'vertical',
                x: 'right',
                data: ['已接受','待处理','已拒绝','已禁止']
            },
            series: [
                {
                    name:'访问来源',
                    type:'pie',                 // pie 饼图
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '30',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:[
                        {value: data.minions.length, name:'已接受'},
                        {value: data.minions_pre.length, name:'待处理'},
                        {value: data.minions_rejected.length, name:'已拒绝'},
                        {value: data.minions_denied.length, name:'已禁止'},
                    ]
                }
            ]
        };
        keyListWidget.setOption(option);
    },
    renderStatusChart: function(data){
        var online = offline = 0;
        for(i in data){
            if(data[i]) online ++;
            else offline ++;
        }
        var count = online + offline;
        var statusListWidget = echarts.init(document.getElementById('status-chart'));
        var option = {
            title: {
                text: '主机状态'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b}: {c} ({d}%)"
            },
            legend: {                           // 图例
                orient: 'vertical',
                x: 'right',
                data: ['在线', '离线']
            },
            series: [
                {
                    name:'访问来源',
                    type:'pie',                 // pie 饼图
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '30',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:[
                        {value: online, name:'在线'},
                        {value: offline, name:'离线'},
                    ]
                }
            ]
        };
        statusListWidget.setOption(option);
    },
    renderKeyTable: function(result){
        var keysAccepted = [];
        var keysPre = [];
        var keysRejected = [];
        var keysDenied = [];
    
        for(var i = 0; i < result.minions.length; i ++ ){
            keysAccepted.push({minionId: result.minions[i]});
        }
        $('#minions-accepted').bootstrapTable('load', keysAccepted);
    
        for(var i = 0; i < result.minions_pre.length; i ++ ){
            keysPre.push({minionId: result.minions_pre[i]});
        }
        $('#minions-pre').bootstrapTable('load', keysPre);
    
        for(var i = 0; i < result.minions_rejected.length; i ++ ){
            keysRejected.push({minionId: result.minions_rejected[i]});
        }
        $('#minions-rejected').bootstrapTable('load', keysRejected);
    
        for(var i = 0; i < result.minions_denied.length; i ++ ){
            keysDenied.push({minionId: result.minions_denied[i]});
        }
        $('#minions-denied').bootstrapTable('load', keysDenied);
    },
    
    keysOperation: function(e){
        var self = this;
        // key-delete, key-deny, 捕获操作方法字符串
        var pattern = new RegExp('\.key-(.*)$');
        var cls = $(e.target).attr('class');
        var operation = pattern.exec(cls)[1];
        console.log($(e.target).parents('tr').find('.minion-id').text());
        $.ajax({
            type: 'GET',
            url: apiList.key[operation],
            data: {
                match: $(e.target).parents('tr').find('.minion-id').text()
            },
            success: function(result){
                self.postRequest(result);
            }
        });
    },
    postRequest: function(result){
        console.log(result);
        var self = this;
        if(result.return[0].data.success){
            $.gritter.add({
                title: '操作成功',
                class_name: 'gritter-success'
            });
            self.refreshKeys();
            self.refreshStatus();
        }else{
            $.gritter.add({
                title: '操作失败',
                class_name: 'gritter-error'
            });
        }
    },
});

var mainView = new MainView();
console.log('dashboard start');
}

app.modules.Dashboard = Dashboard;

})();